using System;
using System.Collections;
using Sirenix.OdinInspector.Editor;
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using Editor.AtlasTools;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor.Drawers;
using Sirenix.Utilities;
using Sirenix.Utilities.Editor;
using UnityEditor;

public class MultiSelectImageGridDrawer<TArray> : TwoDimensionalArrayDrawer<TArray, AtlasSpriteInfo> where TArray : IList
{
    private HashSet<Vector2Int> selectedCells = new HashSet<Vector2Int>();
    private Vector2Int selectionStart;
    private bool isDragging;
    private SelectionMode currentMode;

    private enum SelectionMode
    {
        None,
        Single,
        Additive,
        Range
    }

    protected override TableMatrixAttribute GetDefaultTableMatrixAttributeSettings()
    {
        return new TableMatrixAttribute()
        {
            SquareCells = true,
            HideColumnIndices = true,
            HideRowIndices = true,
            RowHeight = 64,
        };
    }
    // 新增滚动位置记录
    private Vector2 scrollPosition = Vector2.zero;
    protected override void DrawPropertyLayout(GUIContent label)
    {
        // 添加滚动区域
        try
        {
            scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
            base.DrawPropertyLayout(label);
            GUILayout.EndScrollView();
        }
        catch (Exception e)
        {
           Debug.Log(e);
        }

    }
    protected override AtlasSpriteInfo DrawElement(Rect rect, AtlasSpriteInfo value)
    {
        // 调整坐标计算（考虑滚动偏移）
        var cellPos = new Vector2Int(
            (int)(rect.x - scrollPosition.x),
            (int)(rect.y - scrollPosition.y)
        );

        // 绘制单元格内容
        if (value?.texture != null)
        {
            GUI.DrawTexture(rect.AlignCenterXY(rect.width - 4), value.texture, ScaleMode.ScaleToFit);
        }
        else
        {
            GUI.Label(rect, "Empty", SirenixGUIStyles.CenteredGreyMiniLabel);
        }

        if (value?.Name != null)
        {
            var countRect = rect.Padding(2).AlignBottom(16);
            if (GUI.Button(countRect, (value.Name), SirenixGUIStyles.Button))
            {
                // 通过Texture获取资源路径
                string path = AssetDatabase.GetAssetPath(value.texture);
                if (!string.IsNullOrEmpty(path))
                {
                    // 定位到资源文件
                    UnityEngine.Object obj = AssetDatabase.LoadMainAssetAtPath(path);
                    EditorGUIUtility.PingObject(obj);
                }
            }
            else 
            {
                HandleCellInteraction(rect, cellPos);
            }
        }

        // 绘制选中状态
        if (value != null)
        {
            if (selectedCells.Contains(cellPos))
            {
                value.isSelected = true;
                EditorGUI.DrawRect(rect, new Color(0.3f, 0.7f, 1f, 0.5f));
            }
            else
            {
                value.isSelected = false;
            }
        }

        return value;
    }

    private void HandleCellInteraction(Rect rect, Vector2Int cellPos)
    {
        Event evt = Event.current;
        
        if (evt.type == EventType.MouseDown && rect.Contains(evt.mousePosition))
        {
            StartSelection(cellPos);
            // evt.Use();
        }
        else if (isDragging && evt.type == EventType.MouseDrag)
        {
            UpdateSelection(cellPos);
            // evt.Use();
        }
        else if (evt.type == EventType.MouseUp)
        {
            FinalizeSelection();
            // evt.Use();
        }
    }

    private void StartSelection(Vector2Int cell)
    {
        isDragging = true;

        if (Event.current.control)
        {
            currentMode = SelectionMode.Additive;
            ToggleCellSelection(cell);
        }
        else if (Event.current.shift)
        {
            currentMode = SelectionMode.Range;
            selectionStart = GetRangeStartPoint();
            UpdateRangeSelection(cell);
        }
        else
        {
            currentMode = SelectionMode.Single;
            if (selectedCells.Count == 1 && selectedCells.Contains(cell))
            {
                selectedCells.Clear();
            }
            else
            {
                selectedCells.Clear();
                selectedCells.Add(cell);
                selectionStart = cell;
            }
        }

        GUI.changed = true;
    }

    private void UpdateSelection(Vector2Int currentCell)
    {
        switch (currentMode)
        {
            case SelectionMode.Range:
                UpdateRangeSelection(currentCell);
                break;
            case SelectionMode.Single:
                UpdateRangeSelection(currentCell);
                break;
        }
    }

    private void UpdateRangeSelection(Vector2Int endCell)
    {
        HashSet<Vector2Int> newSelection = new HashSet<Vector2Int>();

        int minX = Mathf.Min(selectionStart.x, endCell.x);
        int maxX = Mathf.Max(selectionStart.x, endCell.x);
        int minY = Mathf.Min(selectionStart.y, endCell.y);
        int maxY = Mathf.Max(selectionStart.y, endCell.y);

        for (int x = minX; x <= maxX; x++)
        {
            for (int y = minY; y <= maxY; y++)
            {
                newSelection.Add(new Vector2Int(x, y));
            }
        }

        if (currentMode == SelectionMode.Range)
        {
            selectedCells.UnionWith(newSelection);
        }
        else
        {
            selectedCells = newSelection;
        }

        GUI.changed = true;
    }

    private Vector2Int GetRangeStartPoint()
    {
        return selectedCells.Count > 0 ? selectedCells.Last() : selectionStart;
    }

    private void ToggleCellSelection(Vector2Int cell)
    {
        if (!selectedCells.Add(cell))
            selectedCells.Remove(cell);
    }

    private void FinalizeSelection()
    {
        isDragging = false;
        currentMode = SelectionMode.None;
    }

}